/*
 * Copyright 2008 the original author Ang Gao.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * GoogleSearcher.java 2008-11-12
 */
package ie.ucc.cs.anggao.finalproject.client.support.searchengine;

import ie.ucc.cs.anggao.finalproject.client.model.SearchEngine;
import ie.ucc.cs.anggao.finalproject.client.model.SearchEngineResult;
import ie.ucc.cs.anggao.finalproject.client.ui.mainpanel.infopane.InfoPane;

import com.google.gwt.search.client.SearchCompleteHandler;
import com.google.gwt.search.client.SearchControl;
import com.google.gwt.search.client.SearchControlOptions;
import com.google.gwt.search.client.WebResult;
import com.google.gwt.search.client.WebSearch;

/**
 * @author GaoAng
 *
 */
public class GoogleSearcher extends BaseSearcher{

	public GoogleSearcher(InfoPane view) {
		super(view, new SearchEngine("Google Search", "http://www.google.com"));
	}
	
	
	public void doIR(String q) {
		System.out.println("Google Search: "+ q);
		
		getView().clearResults();
		SearchControlOptions options = new SearchControlOptions();
		
		WebSearch webSearch = new WebSearch();
		webSearch.setNoHtmlGeneration();
		options.add(webSearch);
		final SearchControl control = new SearchControl(options);
		
		control.addSearchCompleteHandler(new SearchCompleteHandler() {

			public void onSearchComplete(SearchCompleteEvent event) {
				WebSearch search = (WebSearch) event.getSearch();
				WebResult result = (WebResult) event.getResult();
		
				
				String url = result.getUrl();
				if(url != null){
					String title = result.getTitle();
					String summary = result.getContent();
					getView().addSearchResult(new SearchEngineResult(title, url, summary));
				}
			}

		});

		control.execute(q);
	}
	

}

